import os
import re

import requests


def train(data):
    url = "http://127.0.0.1:5000/api/v0/train"
    # 发送POST请求
    response = requests.post(url, json=data)
    # 检查响应状态码
    if response.status_code == 200:
        # 打印响应内容
        print("Response:")
        print(response.text)
    else:
        print("Error:", response.status_code)

def read_sql_scripts(directory):
    # Dictionary to hold the contents of each SQL file
    sql_contents = {}

    # Walk through the directory
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.sql'):
                file_path = os.path.join(root, file)

                # Read the file
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()

                    # Split the content by empty lines
                    groups = re.split(r'\n\s*\n', content.strip())

                    # Store the groups in the dictionary
                    sql_contents[file] = groups

    return sql_contents


def read_sql_file(file_path):
    # Dictionary to hold the contents of each SQL file
    sql_contents = {}

    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

        # Split the content by empty lines
        groups = re.split(r'\n\s*\n', content.strip())

        # Store the groups in the dictionary
        sql_contents[f] = groups

    return sql_contents

# Specify the directory containing the SQL files
directory = 'D:/06git/01python/02vanna/02导入训练sql数据/smartlight/data'

# Call the function and print the results
#contents = read_sql_scripts(directory)
contents = read_sql_file("D:/06git/01python/02vanna/02导入训练sql数据/smartlight/data/smartlight-simple2.sql")
for file, groups in contents.items():
    print(f"File: {file}")
    for i, group in enumerate(groups, start=1):
        ddl = {
            "ddl": group
        }
        train(ddl)